package pinkblob.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import pinkblob.entity.ProjectInformation;
import pinkblob.event.ProjectInformationHandler;
import pinkblob.log.Log;
import pinkblob.tools.SetStatus;

public class ProjectManagement extends HttpServlet {

	private String[] StatusNames = {	"Checking requirements", 
										"Waiting for additional information",
										"Estimating prices",
										"Waiting for agreement",
										"Creating/Upating draft",
										"Waiting for draft evaluation",
										"Finalizing Design",
										"",
										"Creating invoice",
										"Waiting for payment",
										"Project finished",
										"",
										"Project brought to court",
										"",
										"Project aborted",
										"Project finished"
									};
	
	private ProjectInformationHandler pih;
	private String view;
	private String action;
	private String update;
	private boolean showall;
	private String pid;
	
	private boolean last_grey = false;
	
	protected Logger log = new Log()
	.getLogger(ProjectManagement.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		pih = new ProjectInformationHandler();

		view = req.getParameter("view");
		log.debug("view: "+view);
		action = req.getParameter("action");
		log.debug("action: "+action);
		update = req.getParameter("update");
		log.debug("update: "+update);
		
		log.debug(req.getRemoteAddr());
		log.debug(req.getLocalAddr());
		log.debug(req.getQueryString());
		log.debug(req.getMethod());
		log.debug(req.getPathInfo());
		log.debug(req.getPathTranslated());
		
		log.debug("load...");
		
		if (view==null) {
			resp.sendRedirect("http://localhost:8080/PinkBlob/projects/?view=list&showall=false");
			return;
		}
		
		String pid = req.getParameter("pid");
		log.debug("pid: "+pid);
		if (pid == null) {
			view = "list";
			action = null;
		}
		
		if (action != null) {
			if (action.equals("abort")){
				pih.abortProject(Integer.parseInt(pid));
			}
		}
		
		String showallquery = req.getParameter("showall");
		if (showallquery != null) {
			showall = Boolean.parseBoolean(showallquery);
		} else {
			showall = false;
		}
		
		if (update != null && update.equals("payment") && pid != null) {
			log.debug("payment received");
			pih.setStatus(Integer.parseInt(pid), 15);
			resp.sendRedirect("http://localhost:8080/PinkBlob/projects/?view=detail&pid=" + pid );	
		}
		
		if (update != null && update.equals("true") && pid != null) {
			System.out.println("updating dl...");
			String new_dl = req.getParameter("new_dl").trim();
			log.debug(new_dl);
			String day = new_dl.substring(0,2);
			day = (day.startsWith("0")) ? day.substring(1) : day;
			String month = new_dl.substring(3,5);
			month = (month.startsWith("0")) ? month.substring(1) : month;
			String year = new_dl.substring(6,8);
			year = "1"+year;
			String hour = new_dl.substring(9,11);
			hour = (hour.startsWith("0")) ? hour.substring(1) : hour;
			String minute = new_dl.substring(12,14);
			minute = (minute.startsWith("0")) ? minute.substring(1) : minute;
			
			int day_i = Integer.parseInt(day);
			int month_i = Integer.parseInt(month) - 1;
			int year_i = Integer.parseInt(year);
			int hour_i = Integer.parseInt(hour);
			int minute_i = Integer.parseInt(minute);
			
			log.debug(year+"-"+month+"-"+day+" "+hour+"-"+minute);
			Date mydate = new Date(year_i,month_i,day_i,hour_i,minute_i);
			log.debug("date: "+mydate);
			pih.setNewDeadline(Integer.parseInt(pid), mydate);
			resp.sendRedirect("http://localhost:8080/PinkBlob/projects/?view=detail&pid=" + pid );
		}
		
		if (view.equals("list")) {
			renderProjectList(resp.getWriter());
		} else if (view.equals("detail")) {
			renderDetail(resp.getWriter(), req.getParameter("pid"));
		}
		
		
		
	}
	
	private void renderHeader(PrintWriter out) {
		out.println("<html>");
		out.println("<head>");
		out.println("<title>PinkBlob - ISS Projects</title>");
		out.println("<style type='text/css'><!--");
		//out.println("#header {width:100%; height:70px; background: url(../skins/grey/images/top.jpg) no-repeat}");
		out.println("a:link { font-weight:bold; color:blue; text-decoration:none; }");
		out.println("a:visited { font-weight:bold; color:blue; text-decoration:none; }");
		out.println("a:focus { font-weight:bold; color:red; text-decoration:underline; }");
		out.println("a:hover { font-weight:bold; color:pink; text-decoration:none; }");
		out.println("a:active { font-weight:bold; color:lime; text-decoration:underline; }");
		out.println("body {background: #CCC; font-family: Verdana}");
		out.println("td {border: solid #000 1pt; padding: 2px}");
		out.println("tr.header {font-weight:bold}");
		out.println("tr.odd { background-color: #B5B5B5 }");
		out.println("tr.evn { background-color: #EEEEEE}");
		out.println("table {border-collapse: collapse}");
		out.println("");
		out.println("//--></style>");
		out.println("</head>");
		out.println("<body>");
		out.println("<div id='header' > </div>");
	}
	
	private void renderFooter(PrintWriter out) {
		out.println("</body>");
		out.println("</html>");
	}
	
	private void renderProjectList(PrintWriter out) {
		renderHeader(out);
		
		List<ProjectInformation> projects = pih.getAllProjectInformation(showall);
		
		if (showall) {
			out.println("<a href=http://localhost:8080/PinkBlob/projects/?view=list&showall=false>show only running processes</a>");
		} else {
			out.println("<a href=http://localhost:8080/PinkBlob/projects/?view=list&showall=true>show all processes</a>");
		}
		
		out.println("<table>");
		out.println("<tr class=header><td width='120'>Project ID</td><td width='500'>Status</td><td width='200'>Deadline</td></tr>");
		
		boolean tr_grey = false;
		for (ProjectInformation pi : projects) {
			tr_grey = !tr_grey;
			if (tr_grey) out.println("<tr class=\"odd\">"); 
			else out.println("<tr class=\"evn\">");
			out.println("<td>");
			out.println("<a href=?view=detail&pid=" + pi.getProjectID() + ">" + pi.getProjectID() + "</a>");
			out.println("</td>");
			out.println("<td>");
			out.println(StatusNames[pi.getStatus()]);
			out.println("</td>");
			out.println("<td>");
			out.println(SimpleDateFormat.getInstance().format(pi.getDeadline()));
			out.println("</td>");
			out.println("</tr>");
		}
		
		out.println("</table>");		
		
		renderFooter(out);
	}
	
	private void renderDetail(PrintWriter out, String ProjectID) {
		try { 
			ProjectInformation pi = pih.getProjectInformation(Integer.parseInt(ProjectID));
		
			renderHeader(out);
			out.println("<a href=http://localhost:8080/PinkBlob/projects/?view=list&showall=false>Back</a><br> ");
			if (pi.getStatus()%2 == 1 && pi.getStatus() < 10) {
				out.println("<a href=javascript:void onClick=\"if(confirm('Really abort this project?')) window.location = 'http://localhost:8080/PinkBlob/projects/?view=list&showall=false&action=abort&pid=" + pi.getProjectID() + "';\">Abort Project</a>");
			}
			out.println("<table>");
			out.println("<tr><td width=200>Project ID</td><td width=816>" + pi.getProjectID() + "</td></tr>");
			out.println(renderDetailRow("Status", StatusNames[pi.getStatus()]));
			out.println(renderDetailRow("Deadline", SimpleDateFormat.getInstance().format(pi.getDeadline())));
			out.println(renderDetailRow("High Priority", pi.getHighPriority().toString()));
			out.println(renderDetailRow("Text Design", pi.getTextDesign().toString()));
			out.println(renderDetailRow("Graphic Design", pi.getGraphicDesign().toString()));
			out.println(renderDetailRow("Design Requirements", pi.getDesignRequirements()));
			out.println(renderDetailRow("Additional Information Need", pi.getCR_InformationRequest()));
			out.println(renderDetailRow("Cost Estimate", pi.getEPMA_CostEstimate()));
			out.println(renderDetailRow("Aggreement State", pi.getAgreement_State()));
			out.println(renderDetailRow("Draft", pi.getD_Draft()));
			out.println(renderDetailRow("Draft Comment", pi.getD_DraftComment()));
			out.println(renderDetailRow("Evaluation Details", pi.getEvaluationDetails()));
			out.println(renderDetailRow("Final Price", pi.getPrice().toString()));
			out.println(renderDetailRow("Bill", pi.getBill()));
			out.println(renderDetailRow("Iterations", String.valueOf(pi.getIterations())));			
			out.println(renderDetailRow("Admonitions sent", pi.getII_AdmonitionCounter().toString()));
			
			
			out.println("</table>");
			
			out.println("<form action=\"http://localhost:8080/PinkBlob/projects/\" method=\"get\">");
			out.println("<input type=\"hidden\" name=\"update\" value=\"true\">");
			out.println("<input type=\"hidden\" name=\"showall\" value=\"false\">");
			out.println("<input type=\"hidden\" name=\"view\" value=\"detail\">");
			out.println("<input type=\"hidden\" name=\"pid\" value=\""+pi.getProjectID()+"\">");
			out.println("Set new Deadline: <input type=\"text\" name=\"new_dl\" value=\""+SimpleDateFormat.getInstance().format(pi.getDeadline())+"\">");
			out.println("<input type=\"submit\" value=\"Update Project Information\">");
			out.println("</form>");
			
			out.println("<br>");
			out.println("<form action=\"http://localhost:8080/PinkBlob/projects/\" method=\"get\">");
			out.println("<input type=\"hidden\" name=\"update\" value=\"payment\">");
			out.println("<input type=\"hidden\" name=\"showall\" value=\"false\">");
			out.println("<input type=\"hidden\" name=\"view\" value=\"detail\">");
			out.println("<input type=\"hidden\" name=\"pid\" value=\""+pi.getProjectID()+"\">");
			out.println("<input type=\"submit\" value=\"Mark as 'Payment Received'!\">");
			out.println("</form>");
			
			out.println("<iframe src='http://localhost:8080/PinkBlob/filebrowser/?pid=" + pi.getProjectID() + "&specialFlag=noFlag' name='filebrowser' width='600' height='215' frameborder='0'>");
			out.println("Your Browser does not support Iframes");
			out.println("</iframe>");
		
			renderFooter(out);
		} catch (Exception e) {
			out.println("An unknown error occured");
		}
	}
	
	private String renderDetailRow(String label, String value) {
		if (value != null && !value.equals("")) {
			String result = (last_grey) ? "<tr class=\"odd\"><td>" + label + "</td><td>" + value.replace("\n", "<br />") + "</td></tr>"
			: "<tr class=\"evn\"><td>" + label + "</td><td>" + value.replace("\n", "<br />") + "</td></tr>";
			last_grey = !last_grey;
			return result;
		} else {
			return "";
		}
	}
	
}
